<?php

require_once 'HttpClientAuth.php';
require_once 'Zend/Http/Client.php';


/**
 * Description of VirtuaLabRest_HttpClient_Client
 *
 * @author markos
 */
class HttpClient {

    protected $_log;
    protected $_client;
    protected $_username;
    protected $_auth;
    protected $_uri;
    protected $_http_method;
    protected $_cookie;

    public function __construct($log) {
        $config = new Zend_Config_Ini(CONFIGURATION_FILE, APPLICATION_ENV);
        $this->_uri = $config->get('endpoint');
        $this->_http_method = $config->get('http_method');
        $this->_client = new Zend_Http_Client();
        $this->_auth = new HttpClientAuth();
        $this->_log = $log;
    }

    /**
     * Efectua la invocacion HTTP al API. Esta funcion no tiene idea de que 
     * envia, solo realiza la peticion y retorna la respuesta, sin nocion de 
     * exito e error.
     */
    public function call($params) {
        $params["apiKey"] = $this->_auth->get_apiKey();
        ksort($params, SORT_STRING);
        $query = str_replace(" ", "%20", str_replace("+", "%20", http_build_query($params)));
        $query .= "&signature=" . $this->_auth->getSignature(strtolower($query));
        $this->_client->setUri($this->_uri . $query);
        try {
            $response = $this->_client->request($this->_http_method);
        } catch (Zend_Http_Client_Exception $e) {
            $this->_log->err($e->getMessage());
            $this->_log->err($e->getTraceAsString());
            throw $e;
        }
        $this->_cookie = explode(";", $response->getHeader("Set-cookie"));
        return $response->getBody();
    }

    public function get_cookie() {
        return $this->_cookie;
    }

    public function set_cookie($_cookie) {
        $this->_cookie = $_cookie;
    }

}

?>
